package com.wwj.springcloud.controller;

import com.wwj.springcloud.entity.Dept;
import com.wwj.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptServiceImpl;
    // 获取一些配置信息，得到具体的微服务
    @Autowired
    private DiscoveryClient discoveryClient;

    // http://localhost:8002/dept/add?name=wwj&dbName=2233
    // 80调用要加@RequestBody要不然接收到对象全为null
    @PostMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept) {
        System.out.println("***********");
        System.out.println(dept);
        System.out.println("***********");
        return deptServiceImpl.addDept(dept);
    }

    // http://localhost:8002/dept/get/1
    @GetMapping("/dept/get/{id}")
    public Dept getDeptById(@PathVariable("id") Long deptNo) {
        return deptServiceImpl.queryById(deptNo);
    }

    // http://localhost:8002/dept/getAllDept
    @GetMapping("/dept/getAllDept")
    public List<Dept> getAllDept() {
        return deptServiceImpl.queryAll();
    }

    // http://localhost:8002/dept/discovery
    // 注册进来的微服务，获取一些信息
    @GetMapping("/dept/discovery")
    public Object discovery() {
        // 获得微服务列表的清单
        List<String> services = discoveryClient.getServices();
        System.out.println("discovery==>" + services);

        // 得到一个具体的微服务信息，Eureka注册中心的Application内容
        for (String service : services) {
            System.out.println("=====================" + service + "=====================");
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                System.out.println(
                        instance.getHost() + "\t" +
                                instance.getPort() + "\t" +
                                instance.getUri() + "\t" +
                                instance.getServiceId()
                );
            }
        }
        return this.discoveryClient;
    }

}
